// 创建用户相关仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserinfo, reqLogout } from '@/api/user/index'
import type { UserState } from './types/types.ts'
//  引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type.ts'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token.ts'
// 引入常量路由
import { constantRoute } from '@/router/routes.ts'
const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      avatar: '',
      username: '',
    }
  },
  actions: {
    // 用户登录
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data)
      // console.log(res);
      if (res.code == 200) {
        this.token = res.data as string
        // 本地存储一份token
        SET_TOKEN(res.data as string)
        // 保证当前async可以返回成功promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async userInfo() {
      let res: userInfoResponseData = await reqUserinfo()
      // console.log(res);
      if (res.code == 200) {
        this.avatar = res.data.avatar
        this.username = res.data.name
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    async userLogout() {
      let res: any = await reqLogout()
      // console.log(res);
      if (res.code == 200) {
        this.token = ''
        this.avatar = ''
        this.username = ''
        REMOVE_TOKEN
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
